var Rx = require("rxjs");
var defaultPath = require("path");
var operators = require("rxjs/operators");
var SERVER_CONST = require("../server-const");
var express = require("express");
var router = express.Router();
var model = require("../model/chatModel");
var user = model.user;
var channels = model.channels;
var teams = model.teams;
var channelMembers = model.channelMembers;
var teamMembers = model.teamMembers;
var util = require("../server-util/util");
var mongoose = require("mongoose");
var post = model.post;
var moment = require("moment");
var fs = require("fs");
var files = model.files;
var post = model.post;
var _ = require("lodash");
const { Console } = require("console");
const globalVar = require("../server-util/globalVar");

/**
 * @api {DELETE} /file/delete 删除文件
 * @apiSampleRequest off
 * @apiParam (params) {String} UserId
 * @apiParam (params) {String} FileId
 * @apiGroup file
 */
router.delete("/delete", util.checkAuth, function (req, res) {
	let UserId = mongoose.Types.ObjectId(req.param("UserId"));
	let FileId = mongoose.Types.ObjectId(req.param("FileId"));
	files
		.aggregate([
			{
				$match: {
					_id: {
						$eq: FileId,
					},
				},
			},
		])
		.exec(function (err, fresult) {
			if (!err) {
				fs.unlink(fresult[0].Path, function (deleteError) {
					if (!deleteError) {
						files
							.deleteOne({
								UserId,
								_id: FileId,
							})
							.exec(function (err, result) {
								if (!err) {
									util.getUserInfo(UserId).exec(function (err, result) {
										util.res.success({
											res,
											data: result[0],
										});
									});
								}
							});
					}
				});
			}
		});
});

//获取资源文件
//显示图标数量
//http://localhost:3000/file/resource/icon?action=getColorIconTotal
//显示图标
//http://localhost:3000/file/resource/icon?action=showColorIcon&filename=color_svg_1.svg
router.get("/resource/:type", util.checkAuth, function (req, res) {
	let type = req.param("type");
	let action = req.query.action;
	let filename = req.query.filename;
	//获取图标

	if (action) {
		let dir = "";
		let name = "";

		let getTotal = (dir) => {
			fs.readdir(dir, {}, (err, files) => {
				if (err) {
					util.res.error({
						res,
						msg: err,
					});
				} else {
					if (files && Array.isArray(files)) {
						util.res.success({
							res,
							data: files,
						});
					}
				}
			});
		};

		let sendIcon = (dir, filename) => {
			let name = dir + filename;
			res.sendFile(name, (err) => {
				if (err) {
					res.status(500).send("文件不存在");
				}
			});
		};

		switch (action) {
			//获取其他文件数量
			case globalVar.fileAction.getOtherFileTotal:
				if (type == globalVar.resourceType.other) {
					dir = __dirname + "\\static\\other\\";
				} else {
					res.status(500).send("文件不存在");
				}
				getTotal(dir);
				break;
			//获取黑白图标数量 读取所有文件的名字并返回给前台
			case globalVar.fileAction.getBlackWhiteIconTotal:
				if (type == globalVar.resourceType.icon) {
					dir = __dirname + "\\static\\black_white_icons\\";
				} else {
					res.status(500).send("文件不存在");
				}
				getTotal(dir);
				break;
			//获取彩色图标数量 读取所有文件的名字并返回给前台
			case globalVar.fileAction.getColorIconTotal:
				if (type == globalVar.resourceType.icon) {
					dir = __dirname + "\\static\\color_icons\\";
				} else {
					res.status(500).send("文件不存在");
				}
				getTotal(dir);

				break;
			//获取金融图标数量 读取所有文件的名字并返回给前台
			case globalVar.fileAction.getColorIconTotal:
				if (type == globalVar.resourceType.icon) {
					dir = __dirname + "\\static\\finance_icons\\";
				} else {
					res.status(500).send("文件不存在");
				}

				getTotal(dir);
				break;

			//发送黑白icon到前台显示
			case globalVar.fileAction.showBlackWhiteIcon:
				if (type == globalVar.resourceType.icon) {
					dir = __dirname + "\\static\\black_white_icons\\";
				} else {
					res.status(500).send("文件不存在");
				}

				sendIcon(dir, filename);
				break;

			//发送其他图标或者文件资源到前台
			case globalVar.fileAction.showOtherFile:
				if (type == globalVar.resourceType.other) {
					dir = __dirname + "\\static\\other\\";
				} else {
					res.status(500).send("文件不存在");
				}

				sendIcon(dir, filename);
				break;
			//发送彩色icon到前台显示
			case globalVar.fileAction.showColorIcon:
				if (type == globalVar.resourceType.icon) {
					dir = __dirname + "\\static\\color_icons\\";
				} else {
					res.status(500).send("文件不存在");
				}

				sendIcon(dir, filename);
				break;
			//发送金融icon到前台显示
			case globalVar.fileAction.showFinanceIcon:
				if (type == globalVar.resourceType.icon) {
					dir = __dirname + "\\static\\finance_icons\\";
				} else {
					res.status(500).send("文件不存在");
				}

				sendIcon(dir, filename);
				break;
			default:
				res.status(500).send("文件不存在");
		}
	}
});

/**
 * @api {GET} /file/temp/:Name 查找文件注意这个接口不需要传日期目录
 * @apiSampleRequest off
 * @apiParam (params) {String} Name
 * @apiParam (params) {String} action
 * @apiGroup file
 */
router.get("/temp/:Name", util.checkAuth, function (req, res) {
	let Name = req.param("Name");
	let action = req.query.action;
	files
		.aggregate([
			{
				$match: {
					Name: {
						$eq: Name,
					},
				},
			},
		])
		.exec(function (error, result) {
			if (!!error) {
				res.status(500).send(error);
			} else {
				/* 从物理位置找到文件返回到前台。注意是用Path来sendFile */
				if (!!result && !!result[0] && !!result[0].Path) {
					if (!action) {
						let datafile = result[0];
						if (/(png)|(jpg)|(jpeg)/.test(datafile.Extension)) {
							//图片预览
							res.sendFile(result[0].Path);
						} else {
							//文件下载
							res.download(result[0].Path);
						}
					} else if (action == globalVar.fileAction.view) {
						//图片预览
						res.sendFile(result[0].Path);
					} else if (action == globalVar.fileAction.download) {
						//图片预览
						res.download(result[0].Path);
					}
				} else {
					res.status(500).send("文件不存在");
				}
			}
		});
});

/**
 * @api {POST} /file/share 文件分享
 * @apiSampleRequest off
 * @apiParam (params) {String} UserId
 * @apiParam (params) {String} ChannelId
 * @apiParam (params) {String} PostId
 */
router.post("/share", util.checkAuth, function (req, res) {
	let UserId = mongoose.Types.ObjectId(req.query.UserId);
	let ChannelId = !!req.query.ChannelId
		? mongoose.Types.ObjectId(req.query.ChannelId)
		: null;
	let file = req.query.file;
});

/**
 * @api {POST} /file/upload 上传文件
 * @apiSampleRequest off
 * @apiParam (params) {String} UserId
 * @apiParam (params) {String} ChannelId
 * @apiParam (params) {String} PostId
 * @apiGroup file
 */
router.post("/upload", util.checkAuth, function (req, res) {
	//web端直接通过url传参，android端是post请求，需要通过req.body获取
	let reqUserId = req.query.CreatorId
		? req.query.CreatorId
		: req.body.CreatorId
		? req.body.CreatorId
		: "";
	let reqChannelId = req.query.ChannelId
		? req.query.ChannelId
		: req.body.ChannelId
		? req.body.ChannelId
		: "";
	let reqPostId = req.query.PostId
		? req.query.PostId
		: req.body.PostId
		? req.body.PostId
		: "";
	let reqPostFileType = req.query.PostFileType
		? req.query.PostFileType
		: req.body.PostFileType
		? req.body.PostFileType
		: "";

	let UserId = mongoose.Types.ObjectId(reqUserId);
	let ChannelId = !!reqChannelId ? mongoose.Types.ObjectId(reqChannelId) : null;
	let PostId = !!reqPostId ? mongoose.Types.ObjectId(reqPostId) : null;

	/**********************
	 * PostFileType和Type不一样 PostFileType只有三种，用来区分是否头像或者自定义表情
	 * PostFileType
	 * CustomEmoji : 表情
	 * img : 图片
	 * file : 文件
	 * avatar : 头像
	 *********************/
	if (!req.files || Object.keys(req.files).length === 0) {
		return res.status(400).send("No files were uploaded.");
	}
	let PostFileType = reqPostFileType;
	let MimeType = req.files.mimetype;
	//前台传来的文件
	const file = req.files.file;

	util
		.createFile(file, PostFileType, UserId, ChannelId, PostId, MimeType)
		.then((resultData) => {
			util.res.success({
				res,
				data: resultData.data,
			});
		})
		.catch((err) => {
			util.res.error({
				res,
				msg: err,
			});
		});
});

/**
 * @api {POST} /file/uploadFiles 上传多个文件,批量上传 兼容单文件上传
 * @apiSampleRequest off
 * @apiParam (params) {String} UserId
 * @apiParam (params) {String} ChannelId
 * @apiParam (params) {String} PostId
 * @apiGroup files
 */
router.post("/uploadFiles", util.checkAuth, function (req, res) {
	//web端直接通过url传参，android端是post请求，需要通过req.body获取
	let reqUserId = req.query.CreatorId
		? req.query.CreatorId
		: req.body.CreatorId
		? req.body.CreatorId
		: "";
	let reqChannelId = req.query.ChannelId
		? req.query.ChannelId
		: req.body.ChannelId
		? req.body.ChannelId
		: "";
	let reqPostId = req.query.PostId
		? req.query.PostId
		: req.body.PostId
		? req.body.PostId
		: "";
	let reqPostFileType = req.query.PostFileType
		? req.query.PostFileType
		: req.body.PostFileType
		? req.body.PostFileType
		: "";

	let UserId = mongoose.Types.ObjectId(reqUserId);
	let ChannelId = !!reqChannelId ? mongoose.Types.ObjectId(reqChannelId) : null;
	let PostId = !!reqPostId ? mongoose.Types.ObjectId(reqPostId) : null;

	/**********************
	 * PostFileType和Type不一样 PostFileType只有三种，用来区分是否头像或者自定义表情
	 * PostFileType
	 * CustomEmoji : 表情
	 * img : 图片
	 * file : 文件
	 * avatar : 头像
	 *********************/
	if (!req.files || Object.keys(req.files).length === 0) {
		return res.status(400).send("No files were uploaded.");
	}
	let PostFileType = reqPostFileType;
	let MimeType = req.files.mimetype;
	//前台传来的文件,是数组
	const file = req.files.file;
	var promiseArr = [];

	if (Array.isArray(file)) {
		file.forEach((fa, fi) => {
			promiseArr.push(
				util.createFile(fa, PostFileType, UserId, ChannelId, PostId, MimeType)
			);
		});
	} else {
		promiseArr.push(
			util.createFile(file, PostFileType, UserId, ChannelId, PostId, MimeType)
		);
	}

	Promise.all(promiseArr)
		.then((arrResult) => {
			util.res.success({
				res,
				data: arrResult,
			});
		})
		.catch((errResult) => {
			util.res.error({
				res,
				msg: errResult,
			});
		});
});

/**
 * @api {POST} /file/channelFileList 频道文件
 * @apiSampleRequest off
 * @apiParam (params) {String} ChannelId
 * @apiParam (params) {String} FileType
 * @apiGroup file
 */

router.post("/channelFileList", util.checkAuth, function (req, res) {
	let ChannelId = mongoose.Types.ObjectId(req.body.ChannelId);
	let FileType = req.body.FileType;
	let pageSize = req.body.pageSize;
	let pageNum = req.body.pageNum - 1;
	let str = req.body.str;

	let callback = function (err, fresult) {
		if (!err) {
			try {
				util.res.success({
					res,
					data: {
						rows: fresult[0].data,
						total: fresult[0].metadata[0].total,
						pageNum: fresult[0].metadata[0].pageNum,
						pageSize: fresult[0].metadata[0].pageSize,
					},
				});
			} catch (error) {
				util.res.success({
					res,
					data: {
						rows: [],
						total: 0,
						pageNum: 1,
						pageSize: 0,
					},
				});
			}
		} else {
			util.res.error({
				res,
				msg: err,
			});
		}
	};
	let aggArr = [];
	if (FileType == "链接") {
		//关键字搜索
		let querySearch = null;
		if (str) {
			querySearch = {
				$match: {
					Type: "url",
					ChannelId,
					Message: {
						$in: [new RegExp(str)],
					},
				},
			};
		} else {
			querySearch = {
				$match: {
					Type: "url",
					ChannelId,
				},
			};
		}

		aggArr = [
			querySearch,

			{
				$lookup: {
					from: "users",
					localField: "UserId",
					foreignField: "_id",
					as: "createor",
				},
			},
			{
				$project: {
					CreateAt: "$CreateAt",
					DisplayName: "$DisplayName",
					createor: "$createor.Username",
					Type: "$Type",
					Message: "$Message",
					ChannelId: "$ChannelId",
				},
			},
			{
				$facet: {
					metadata: [
						{
							$count: "total",
						},
						{
							$addFields: {
								pageNum: req.body.pageNum,
								pageSize: pageSize,
							},
						},
					],
					data: [
						{
							$skip: pageNum * pageSize,
						},
						{
							$limit: pageSize,
						},
					],
				},
			},
		];
		post.aggregate(aggArr).exec(callback);
	} else {
		let query = {};

		//关键字搜索
		let querySearch = null;
		if (FileType === "文件") {
			query = {
				$not: {
					$in: ["jpg", "png", "bmp", "gif"],
				},
			};
		} else if (FileType === "图片") {
			query = { $in: ["jpg", "png", "bmp", "gif"] };
		}
		if (str) {
			querySearch = {
				$match: {
					ChannelId,
					FileType: query,
					Message: {
						$in: [new RegExp(str)],
					},
				},
			};
		} else {
			querySearch = {
				$match: {
					ChannelId,
					FileType: query,
				},
			};
		}

		aggArr = [
			querySearch,
			{
				$lookup: {
					from: "users",
					localField: "UserId",
					foreignField: "_id",
					as: "createor",
				},
			},

			{
				$project: {
					FileType: "$FileType",
					CreateAt: "$CreateAt",
					PreviewPath: "$PreviewPath",

					DisplayName: "$FileDisplayName",
					Size: "$FileSize",
					createor: "$createor.Username",
				},
			},

			/* 
            注意，$facet返回的结果，metadata和data 都是数组
            */
			{
				$facet: {
					metadata: [
						{
							$count: "total",
						},
						{
							$addFields: {
								pageNum: req.body.pageNum, //注意这里不能用pageNum，因为已经减少过1了，返回前台会报错
								pageSize: pageSize,
							},
						},
					],
					data: [
						{
							$skip: pageNum * pageSize,
						},
						{
							$limit: pageSize,
						},
					],
				},
			},
		];
		post.aggregate(aggArr).exec(callback);
	}
});

module.exports = router;
